﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using StackExchange.Redis;


namespace Service
{
    public class ConnectionOptions 
    {
       public string tcp { get; set; } = "127.0.0.1:6379";
       public string password { get; set; } = "";
    }

    public class TransactionService
    {

        readonly ConnectionMultiplexer connection;
        readonly IDatabase dbContext;
        ITransaction transactionContext;
        public TransactionService(ConnectionOptions options = null) 
        {
            options = options ?? new ConnectionOptions();
            ConfigurationOptions configurationOptions = new ConfigurationOptions()
            {
                EndPoints =
                {
                    options.tcp
                },
                Password = options.password
            };
            connection = ConnectionMultiplexer.Connect(configurationOptions);
            dbContext = connection.GetDatabase();
            transactionContext = dbContext.CreateTransaction();
        }
        public ITransaction GetTransaction() 
        {
            return transactionContext;
        }
        public void CreateStringMonitor(Dictionary<string, string> kvs) 
        {
            foreach (var item in kvs)
            {
                transactionContext.AddCondition(Condition.StringEqual(item.Key,item.Value));
            }
        }
        public void CreateStringMonitor(KeyValuePair<string, string> kv)
        {
            transactionContext.AddCondition(Condition.StringEqual(kv.Key, kv.Value));
        }
        public bool Execute() 
        {
            return transactionContext?.Execute() ?? false;
        }
        public void SetString(Dictionary<string, string> kvs,Action<KeyValuePair<string,string>> forevent = null) 
        {
            foreach (var item in kvs)
            {
               forevent?.Invoke(item);
               transactionContext.StringSetAsync(item.Key,item.Value);
            }
        }
        public void SetStringNoMonitor(Dictionary<string, string> kvs, Action<KeyValuePair<string, string>> forevent = null) 
        {
            foreach (var item in kvs)
            {
                forevent?.Invoke(item);
                dbContext.StringSet(item.Key, item.Value);
            }
        }

    }
}
